package com.kadron.paging;

import java.util.Collection;
import java.util.List;

public abstract class AbstractKRowParent implements KRowParent {

	/**
	 * 
	 */
	private static final long serialVersionUID = -874704312881968978L;
	
	private KRowService rowService;
	private ModelContainer modelContainer;
	
	public AbstractKRowParent() {
		super();
	}

	public AbstractKRowParent(ModelContainer modelContainer, KRowService rowService) {
		this();
		this.modelContainer = modelContainer;
		this.rowService = rowService;
	}

	public List<KRow> getElements() {
		return modelContainer.getModels();
	}
	
	public Collection<KRow> getWrappedElements() {
		return modelContainer.getWrapped();
	}
	
	public ModelContainer getModelContainer() {
		return modelContainer;
	}

	public void setModelContainer(ModelContainer modelContainer) {
		this.modelContainer = modelContainer;
	}

	public void show(Integer page) {
		if (page == null || page <= 0 || page > modelContainer.getLast()) {
			return;
		}
		try {			
			modelContainer.setCurrentPage(page);
			final int rows = modelContainer.getRecords();
			final int firstResult = --page*rows;
			rowService.getModels(this, firstResult, rows);
			if (modelContainer.getCount() == null) {
				Long count = rowService.getCount(this);
				modelContainer.setCount(count);
			}
			modelContainer.initPages();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void previous() {
		final int previousPage = modelContainer.getCurrentPage() - 1;
		show(previousPage);						
	}
	
	public void next() {
		final int nextPage = modelContainer.getCurrentPage() + 1;
		show(nextPage);			
	}
	
	public void fastPrev(KRowParent parent) {
		if (parent == null) {
			return;
		}
		final int fastStep = modelContainer.getFastStep();
		final int previousPage = modelContainer.getCurrentPage() - fastStep;
		show(previousPage);						
	}
	
	public void fastNext(KRowParent parent) {
		if (parent == null) {
			return;
		}
		final int fastStep = modelContainer.getFastStep();
		final int nextPage = modelContainer.getCurrentPage() + fastStep;
		show(nextPage);			
	}
	
	public void setRecords(KRowParent parent, Integer records) {
		modelContainer.setRecords(records);
		final int lastPage = modelContainer.getLast();
		final int currentPage = modelContainer.getCurrentPage();
		if (currentPage > lastPage) {
			show(lastPage);
		} else {
			show(currentPage);			
		}
	}
	
	public void setMax(KRowParent parent) {
		modelContainer.setRecords(Integer.MAX_VALUE);
		modelContainer.setCurrentPage(ModelContainer.DEFAULT_PAGE);
		rowService.getAllModels(parent);
	}

	public KRowService getRowService() {
		return rowService;
	}

	public void setRowService(KRowService rowService) {
		this.rowService = rowService;
	}
}
